package com.canyou.config;

import com.canyou.exception.CysWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.cors.CorsUtils;

/**
 * 资源服务器
 *
 * @author cgz
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/oauth/**").permitAll()
                .antMatchers("/websocket_service/**").permitAll()
                .antMatchers("/v2/api-docs", "/v2/api-docs-ext",
                        "/configuration/ui",
                        "/swagger-resources", "/configuration/security",
                        "/doc.html", "/webjars/**", "/favicon.ico").permitAll()
                .antMatchers("/actuator/**").permitAll()
                .antMatchers("/captcha/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resource) {
        // 定义异常转换类生效
        OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        authenticationEntryPoint.setExceptionTranslator(new CysWebResponseExceptionTranslator());
        resource.authenticationEntryPoint(authenticationEntryPoint);
        resource.tokenStore(tokenStore);
    }
}